/**
 *
 * @author zzhijie
 * @date 2021-02-07
 */
import FForm from './form';
import mixin from '../mixins/mixin';
import {getResult} from '../../utils';

export default {
  name: 'f-search',
  mixins: [mixin],
  props: {
    config: {
      type: Object,
      default: () => ({})
    },
    page: {
      type: Object,
      default: () => ({})
    }
  },
  components: {
    FForm
  },
  data() {
    return {
      params: {},
      slideFlag: false,
      visibleNum: Number.MAX_SAFE_INTEGER,
      crudConfig: this.$getGlobalConfig('crud')
    };
  },
  methods: {
    /**
     * 点击搜索
     */
    handleSearch(resetCurrentPage = true) {
      let {current = 'currentPage'} = this.config.pageProp || this.crudConfig.pageProp || {};
      if (resetCurrentPage) this.page[current] = 1;
      this.emitEvent('submit-search', this.params);
    },
    /**
     * 重置搜索栏字段
     */
    handleReset() {
      this.resetSearchForm();
      let resetSearch = this.$listeners['reset-search'] || this.$listeners['resetSearch'];
      if (resetSearch) {
        this.emitEvent('reset-search', this.params);
      } else {
        this.handleSearch();
      }
    },
    /**
     * 重置搜索栏字段
     */
    resetSearchForm() {
      let params = {};
      this.config.columns.forEach(column => {
        let {$search = {}} = column;
        let {hide, value} = $search;
        if (!getResult(hide)) {
          params[column.field] = getResult(value);
        }
      });
      this.params = params;
    },
    /**
     * 折叠搜索栏
     */
    handleSlide() {
      this.slideFlag = !this.slideFlag;
      this.setVisibleNum();
    },
    /**
     * 设置搜索栏可显示表单组件数量
     */
    setVisibleNum(initFlag) {
      let {collapsible = false, searchable = true} = this.config;
      // 开启折叠搜索栏
      if (collapsible && searchable) {
        let margin = 10;
        let searchBar = this.$refs.searchBar.$el;
        let searchOpt = this.$refs.searchOpt.$el;
        let items = searchBar.children;
        let visibleWidth = searchBar.offsetWidth;
        let totalWidth = searchOpt.offsetWidth + margin * 2;
        let visibleNum = 1;
        [].forEach.call(items, (item, i) => {
          if (item === searchOpt) return;
          totalWidth += item.offsetWidth + margin;
          if (this.slideFlag || totalWidth < visibleWidth) {
            visibleNum = i + 1;
            item.style.display = '';
          } else {
            item.style.display = 'none';
          }
        });
        if (initFlag) this.visibleNum = visibleNum;
      }
    },
    buildBtn() {
      let searchBtn = this.config.$searchBtn || this.crudConfig.$searchBtn || {
        hide: false,
        text: '搜索',
        props: {type: 'primary', icon: 'el-icon-search'},
        attrs: {}
      };
      let resetBtn = this.config.$resetBtn || this.crudConfig.$resetBtn || {
        hide: false,
        text: '重置',
        props: {icon: 'el-icon-refresh'},
        attrs: {}
      };
      return (
        <el-form-item class="search-opt" ref="searchOpt">
          {!searchBtn.hide && <el-button props={searchBtn.props} attrs={searchBtn.attrs}
                                         on-click={this.handleSearch}>{searchBtn.text}</el-button>}
          {!resetBtn.hide && <el-button props={resetBtn.props} attrs={resetBtn.attrs}
                                        on-click={this.handleReset}>{resetBtn.text}</el-button>}
          {this.$scopedSlots.search && this.$scopedSlots.search()}
        </el-form-item>
      );
    },
    handleKeyup(e) {
      if (e.keyCode === 13) {
        this.handleSearch();
      }
    },
    handleInputChange() {
      let {searchBar} = this.$refs;
      if (!searchBar) return;
      let inputList = searchBar.$el.querySelectorAll('input');
      if (!inputList) return;
      inputList.forEach(input => {
        input.addEventListener('keyup', this.handleKeyup);
      });
    }
  },
  mounted() {
    this.resetSearchForm();
    this.setVisibleNum(true);
    this.handleInputChange();
  },
  render() {
    let {collapsible, columns, attrs = {}} = this.config;
    let searchColumns = columns.filter(v => !getResult(v.$search && v.$search.hide));
    return (
      <div class="search-bar-wrapper" attrs={attrs}>
        <f-form
          ref="searchBar"
          scopeName="$search"
          append={this.buildBtn}
          inline={true}
          validFlag={false}
          config={this.config}
          data={this.params}
          on={this.$listeners}
          scopedSlots={this.$scopedSlots}
        />
        {/*搜索栏折叠*/}
        {collapsible && searchColumns.length > this.visibleNum &&
          <i class={'el-icon-d-arrow-right slide-btn ' + (this.slideFlag ? 'down' : '')}
             on-click={this.handleSlide}> </i>}
      </div>
    );
  }
};
